package com.liyuxiang.graph.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SymptomAnalysisService {
    
    private static final Logger logger = LoggerFactory.getLogger(SymptomAnalysisService.class);
    private final ChatClient chatClient;
    private final ObjectMapper objectMapper;
    
    private static final String SYMPTOM_ANALYSIS_PROMPT = """
            您是一位资深的医疗问诊专家，负责智能分析患者症状并决定下一步问诊策略。
            
            当前对话信息：
            用户输入：{query}
            对话历史：{history}
            已收集症状：{symptoms}
            问诊轮次：{questionCount}
            
            您的任务：
            1. 分析用户当前的描述，提取关键症状信息
            2. 评估已收集信息的完整性
            3. 智能决定是否需要继续询问
            4. 如需继续，生成针对性的问题
            
            症状分析要点：
            - 症状的具体位置和性质
            - 症状的持续时间和发生频率
            - 症状的严重程度和影响
            - 伴随症状和诱发因素
            - 患者的基本情况（年龄、性别相关）
            - 既往病史和家族史
            
            问诊策略：
            - 优先询问最重要的诊断线索
            - 避免重复已经获得的信息
            - 问题要具体、容易理解
            - 考虑患者的描述能力和情绪状态
            
            继续询问的判断标准：
            - 主要症状不够明确
            - 缺少关键的时间、位置、性质信息
            - 症状严重程度不清楚
            - 需要排除紧急情况
            - 问诊轮次少于5次且信息不足
            
            停止询问的条件：
            - 症状信息已经足够做初步判断
            - 问诊轮次超过4次
            - 出现需要紧急就医的征象
            - 患者明确表示不愿继续回答
            
            请严格按照以下JSON格式回复：
            {
              "extractedSymptoms": {
                "主要症状": "从用户描述中提取的主要症状",
                "症状位置": "具体部位",
                "持续时间": "症状持续时间",
                "严重程度": "轻度/中度/重度",
                "伴随症状": "其他相关症状",
                "诱发因素": "可能的诱发因素"
              },
              "shouldContinue": true/false,
              "confidence": 0.0-1.0,
              "nextQuestion": "如果继续询问，下一个问题内容",
              "reason": "决策理由",
              "completeness": 0.0-1.0,
              "urgency": "low/medium/high",
              "suggestedAction": "continue/recommend_department/emergency"
            }
            """;
    
    public SymptomAnalysisService(@Qualifier("simpleCharClientBuilder") ChatClient.Builder simpleCharClientBuilder, ObjectMapper objectMapper) {
        this.chatClient = simpleCharClientBuilder.build();
        this.objectMapper = objectMapper;
    }
    
    public SymptomAnalysisResult analyzeSymptom(String query, List<String> conversationHistory, 
                                              Map<String, Object> currentSymptoms, int questionCount, String userId) {
        logger.info("开始AI症状分析 - 用户ID: {}, 问诊轮次: {}, 已收集症状数: {}", userId, questionCount, currentSymptoms.size());
        
        try {
            String historyText = conversationHistory.isEmpty() ? "无对话历史" : String.join("\n", conversationHistory);
            String symptomsText = formatSymptoms(currentSymptoms);
            
            String prompt = SYMPTOM_ANALYSIS_PROMPT
                    .replace("{query}", query)
                    .replace("{history}", historyText)
                    .replace("{symptoms}", symptomsText)
                    .replace("{questionCount}", String.valueOf(questionCount));
            
            logger.info("发送症状分析请求 - 提示长度: {}", prompt.length());
            
            String aiResponse = chatClient.prompt()
                    .user(prompt)
                    .call()
                    .content();
            
            logger.info("收到AI症状分析响应: {}", aiResponse);
            
            SymptomAnalysisResult result = parseSymptomAnalysisResponse(aiResponse);
            
            logger.info("症状分析完成 - 用户ID: {}, 继续询问: {}, 完整度: {}, 紧急度: {}", 
                    userId, result.shouldContinue, result.completeness, result.urgency);
            
            return result;
            
        } catch (Exception e) {
            logger.error("AI症状分析失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return getFallbackSymptomAnalysis(query, currentSymptoms, questionCount, userId);
        }
    }
    
    private SymptomAnalysisResult parseSymptomAnalysisResponse(String response) {
        try {
            int startIndex = response.indexOf('{');
            int endIndex = response.lastIndexOf('}') + 1;
            
            if (startIndex >= 0 && endIndex > startIndex) {
                String jsonStr = response.substring(startIndex, endIndex);
                JsonNode jsonNode = objectMapper.readTree(jsonStr);
                
                Map<String, Object> extractedSymptoms = objectMapper.convertValue(
                        jsonNode.get("extractedSymptoms"), Map.class);
                boolean shouldContinue = jsonNode.get("shouldContinue").asBoolean(true);
                double confidence = jsonNode.get("confidence").asDouble(0.5);
                String nextQuestion = jsonNode.get("nextQuestion").asText("");
                String reason = jsonNode.get("reason").asText("AI分析结果");
                double completeness = jsonNode.get("completeness").asDouble(0.3);
                String urgency = jsonNode.get("urgency").asText("low");
                String suggestedAction = jsonNode.get("suggestedAction").asText("continue");
                
                return new SymptomAnalysisResult(extractedSymptoms, shouldContinue, confidence, 
                        nextQuestion, reason, completeness, urgency, suggestedAction, true);
            }
        } catch (Exception e) {
            logger.warn("解析症状分析JSON失败，尝试文本解析: {}", e.getMessage());
        }
        
        return parseTextSymptomResponse(response);
    }
    
    private SymptomAnalysisResult parseTextSymptomResponse(String response) {
        Map<String, Object> symptoms = Map.of("描述", response.substring(0, Math.min(100, response.length())));
        boolean shouldContinue = response.contains("继续") || response.contains("询问");
        String nextQuestion = "请详细描述一下您的症状情况？";
        
        return new SymptomAnalysisResult(symptoms, shouldContinue, 0.6, 
                nextQuestion, "基于文本简单解析", 0.4, "low", "continue", false);
    }
    
    private SymptomAnalysisResult getFallbackSymptomAnalysis(String query, Map<String, Object> currentSymptoms, 
                                                           int questionCount, String userId) {
        logger.warn("使用备用症状分析逻辑 - 用户ID: {}", userId);
        
        // 检查输入是否为无效内容
        if (isInvalidInput(query)) {
            return new SymptomAnalysisResult(new HashMap<>(), false, 0.9,
                    "您的输入似乎与健康问题无关，请告诉我您有什么身体不适吗？", 
                    "检测到无效输入，停止症状收集", 0.0, "low", "redirect_to_conversation", false);
        }
        
        // 提取用户输入中的关键信息
        Map<String, Object> extractedSymptoms = extractBasicSymptoms(query);
        
        // 简单的继续询问逻辑
        boolean shouldContinue = questionCount < 3 && currentSymptoms.size() < 4 && !extractedSymptoms.isEmpty();
        
        String nextQuestion = shouldContinue ? generateBasicQuestion(questionCount) : 
                             "感谢您提供的信息，让我来为您推荐合适的科室。";
        String suggestedAction = shouldContinue ? "continue" : "recommend_department";
        
        String reason = "备用分析：基于问诊轮次和症状数量判断";
        double completeness = Math.min(0.8, (currentSymptoms.size() + extractedSymptoms.size()) * 0.25);
        
        return new SymptomAnalysisResult(extractedSymptoms, shouldContinue, 0.7, 
                nextQuestion, reason, completeness, "low", suggestedAction, false);
    }
    
    private boolean isInvalidInput(String query) {
        String lowerQuery = query.toLowerCase().trim();
        
        // 检查侮辱性词汇
        String[] inappropriateWords = {"笨蛋", "傻逼", "白痴", "蠢货", "混蛋", "垃圾", "废物"};
        for (String word : inappropriateWords) {
            if (lowerQuery.contains(word)) {
                return true;
            }
        }
        
        // 检查无意义输入
        if (query.trim().length() <= 2 || 
            query.matches("^[a-zA-Z]{1,3}$") ||  // 单个英文字母
            query.matches("^\\d+$")) {  // 纯数字
            return true;
        }
        
        // 检查明显非医疗相关内容
        String[] nonMedicalInputs = {"哈哈", "呵呵", "测试", "试试", "随便", "无聊"};
        for (String nonMedical : nonMedicalInputs) {
            if (lowerQuery.contains(nonMedical)) {
                return true;
            }
        }
        
        return false;
    }
    
    private Map<String, Object> extractBasicSymptoms(String query) {
        Map<String, Object> symptoms = new java.util.HashMap<>();
        
        if (!query.trim().isEmpty()) {
            symptoms.put("用户描述", query.trim());
            
            // 简单的关键词提取
            String lowerQuery = query.toLowerCase();
            if (lowerQuery.contains("痛") || lowerQuery.contains("疼")) {
                symptoms.put("症状性质", "疼痛");
            }
            if (lowerQuery.contains("头") || lowerQuery.contains("脑")) {
                symptoms.put("症状位置", "头部");
            }
            if (lowerQuery.contains("天") || lowerQuery.contains("周") || lowerQuery.contains("月")) {
                symptoms.put("持续时间", "需进一步确认");
            }
        }
        
        return symptoms;
    }
    
    private String generateBasicQuestion(int questionCount) {
        String[] basicQuestions = {
            "请详细描述一下您的主要症状，比如具体是哪里不舒服？",
            "这个症状大概持续多长时间了？是最近才出现的吗？",
            "症状的严重程度如何？会不会影响到您的日常生活？",
            "还有其他伴随的症状吗？比如发热、恶心等？",
            "有什么因素会让症状加重或者缓解吗？"
        };
        
        if (questionCount < basicQuestions.length) {
            return basicQuestions[questionCount];
        } else {
            return "感谢您提供的信息，让我来为您分析和推荐合适的科室。";
        }
    }
    
    private String formatSymptoms(Map<String, Object> symptoms) {
        if (symptoms.isEmpty()) {
            return "暂无症状信息";
        }
        
        StringBuilder sb = new StringBuilder();
        symptoms.forEach((key, value) -> {
            sb.append(key).append(": ").append(value).append("\n");
        });
        return sb.toString();
    }
    
    public static class SymptomAnalysisResult {
        private final Map<String, Object> extractedSymptoms;
        private final boolean shouldContinue;
        private final double confidence;
        private final String nextQuestion;
        private final String reason;
        private final double completeness;
        private final String urgency;
        private final String suggestedAction;
        private final boolean fullAiAnalysis;
        
        public SymptomAnalysisResult(Map<String, Object> extractedSymptoms, boolean shouldContinue, 
                                   double confidence, String nextQuestion, String reason, 
                                   double completeness, String urgency, String suggestedAction, boolean fullAiAnalysis) {
            this.extractedSymptoms = extractedSymptoms;
            this.shouldContinue = shouldContinue;
            this.confidence = confidence;
            this.nextQuestion = nextQuestion;
            this.reason = reason;
            this.completeness = completeness;
            this.urgency = urgency;
            this.suggestedAction = suggestedAction;
            this.fullAiAnalysis = fullAiAnalysis;
        }
        
        // Getters
        public Map<String, Object> getExtractedSymptoms() { return extractedSymptoms; }
        public boolean shouldContinue() { return shouldContinue; }
        public double getConfidence() { return confidence; }
        public String getNextQuestion() { return nextQuestion; }
        public String getReason() { return reason; }
        public double getCompleteness() { return completeness; }
        public String getUrgency() { return urgency; }
        public String getSuggestedAction() { return suggestedAction; }
        public boolean isFullAiAnalysis() { return fullAiAnalysis; }
    }
}